﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GWSoft.Clark.EventBus.Common.Events;
using GWSoft.Clark.EventBus.Vehicle.Events;
using Microsoft.AspNetCore.Mvc;

namespace GWSoft.Clark.EventBus.Vehicle.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VehicleController : Controller
    {
        private readonly IEventBus eventBus;

        public VehicleController(IEventBus eventBus)
        {
            this.eventBus = eventBus;
        }

        /// <summary>
        /// 生成一个车辆对象
        /// </summary>
        /// <param name="vehicleNum">车牌号码</param>
        /// <returns></returns>
        [HttpGet("{vehicleNum}")]
        public async Task<IActionResult> Get(string vehicleNum)
        {
            var vehicle = await Task.Factory.StartNew(() => new Models.Vehicle(vehicleNum));
            return Ok(vehicle);
        } 

        /// <summary>
        /// 生成一个车辆
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] dynamic model)
        {
            var vehicleNum = (string)model.VehicleNum;
            if(string.IsNullOrEmpty(vehicleNum))
            {
                return BadRequest();
            }

            var vehicle = new Models.Vehicle(vehicleNum);

            await this.eventBus.PublishAsync(new VehicleCreatedEvent(vehicleNum));

            return Created(Url.Action("Get", new { vehicleNum = vehicleNum}), vehicle.VehicleId);
        }
    }
}